import { DataTypes } from 'sequelize';
import BaseModel from './BaseModel.js';

// 选课状态
const ENROLLMENT_STATUS = {
  SELECTED: 'selected',    // 已选
  DROPPED: 'dropped',     // 已退选
  COMPLETED: 'completed', // 已完成
  FAILED: 'failed'        // 不及格
};

class Enrollment extends BaseModel {
  static initModel(sequelize) {
    const attributes = {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      status: {
        type: DataTypes.ENUM(Object.values(ENROLLMENT_STATUS)),
        defaultValue: ENROLLMENT_STATUS.SELECTED,
        allowNull: false,
      },
      score: {
        type: DataTypes.FLOAT,
        allowNull: true,
        validate: {
          min: 0,
          max: 100,
        },
      },
      feedback: {
        type: DataTypes.TEXT,
        allowNull: true,
      },
      enrolledAt: {
        type: DataTypes.DATE,
        field: 'enrolled_at',
        defaultValue: DataTypes.NOW,
      },
      droppedAt: {
        type: DataTypes.DATE,
        field: 'dropped_at',
        allowNull: true,
      },
      studentId: {
        type: DataTypes.INTEGER,
        field: 'student_id',
        allowNull: false,
        references: {
          model: 'users',
          key: 'id',
        },
      },
      courseId: {
        type: DataTypes.INTEGER,
        field: 'course_id',
        allowNull: false,
        references: {
          model: 'courses',
          key: 'id',
        },
      },
    };

    const options = {
      // 钩子函数
      hooks: {
        beforeUpdate: (enrollment) => {
          // 当状态更新为dropped时，记录退课时间
          if (enrollment.changed('status') && enrollment.status === ENROLLMENT_STATUS.DROPPED) {
            enrollment.droppedAt = new Date();
          }
          
          // 当状态更新为completed时，确保有成绩
          if (enrollment.changed('status') && 
              enrollment.status === ENROLLMENT_STATUS.COMPLETED && 
              !enrollment.score) {
            throw new Error('完成课程需要提供成绩');
          }
        },
      },
    };

    return super.init(sequelize, 'Enrollment', attributes, options);
  }

  // 检查是否可以退课
  canDrop() {
    return this.status === ENROLLMENT_STATUS.SELECTED;
  }

  // 检查是否可以评分
  canGrade() {
    return this.status === ENROLLMENT_STATUS.SELECTED || 
           this.status === ENROLLMENT_STATUS.COMPLETED;
  }

  // 定义关联关系
  static associate(models) {
    // 选课记录属于学生
    this.belongsTo(models.User, {
      foreignKey: 'studentId',
      as: 'student',
    });

    // 选课记录属于课程
    this.belongsTo(models.Course, {
      foreignKey: 'courseId',
      as: 'course',
    });
  }

  // 获取选课状态
  static get STATUS() {
    return ENROLLMENT_STATUS;
  }

  // 转换为JSON时添加额外字段
  toJSON() {
    const values = Object.assign({}, this.get());
    
    // 添加计算字段
    values.canDrop = this.canDrop();
    values.canGrade = this.canGrade();
    
    return values;
  }
}

export default Enrollment;
